const API = (function () {
  // 常量参数
  const BASE_URL = "https://study.duyiedu.com"; //地址
  const TOKEN_KEY = "token"; //令牌

  // http请求函数封装 path：api地址字符串  bodyObj：用于注册，登录等  示例格式：{"loginId": "string","nickname": "string","loginPwd": "string"}
  function get(path) {
    const headers = {};
    // 获取令牌且判断令牌是否有值
    const token = localStorage.getItem(TOKEN_KEY);
    if (token) {
      headers.authorization = `Bearer ${token}`;
    }
    // 获取并返回
    return fetch(BASE_URL + path, { headers });
  }

  function post(path, bodyObj) {
    const headers = {
      "Content-Type": "application/json",
    };
    // 获取令牌且判断令牌是否有值
    const token = localStorage.getItem(TOKEN_KEY);
    if (token) {
      headers.authorization = `Bearer ${token}`;
    }
    // 获取并返回
    return fetch(BASE_URL + path, {
      headers,
      method: "POST",
      body: JSON.stringify(bodyObj),
    });
  }

  // 注册
  async function reg(userInfo) {
    const resp = await post(`/api/user/reg`, userInfo);
    return await resp.json();
  }
  // 登录
  async function login(loginInfo) {
    const resp = await post(`/api/user/login`, loginInfo);
    const result = await resp.json();
    if (result.code === 0) {
      // 登录成功，将响应头中的token保存到localStorage
      const token = resp.headers.get("authorization");
      localStorage.setItem(TOKEN_KEY, token);
    }
    return result;
  }
  // 验证
  async function exists(loginId) {
    const resp = await get(`/api/user/exists?loginId=${loginId}`);
    return await resp.json();
  }
  // 当前登录用户的信息
  async function profile() {
    const resp = await get(`/api/user/profile`);
    return await resp.json();
  }
  // 发送聊天信息
  async function sendChat(content) {
    const resp = await post(`/api/chat`, { content });
    return await resp.json();
  }
  // 查询历史聊天记录
  async function getHistory() {
    const resp = await get("/api/chat/history");
    return await resp.json();
  }
  // 退出登录
  function loginOut() {
    localStorage.removeItem(TOKEN_KEY);
  }
  return {
    reg,
    login,
    exists,
    profile,
    sendChat,
    getHistory,
    loginOut,
  };
})();
